import hashlib

import django_filters
from django.utils.decorators import method_decorator
from django_filters.rest_framework import DjangoFilterBackend
from drf_yasg.utils import swagger_auto_schema
from rest_framework import serializers
from rest_framework.parsers import MultiPartParser, JSONParser
from rest_framework.permissions import IsAuthenticated, BasePermission

from testApp.models import TestImageTable, TestUserTable
from utils.myView import CustomView
from utils.pagination import CustomPagination
from utils.serializer import CustomModelSerializer
from utils.swagger import ViewSwagger
from utils.validator import FileSerializerValidator, CustomValidationError


class TestImageSerializer(CustomModelSerializer):

    class Meta:
        model = TestImageTable
        # fields = '__all__'
        fields = ['id', 'name', 'img', 'create_datetime', 'mime_type', 'file']
        read_only_fields = ['id', 'create_datetime', 'mime_type']
        extra_kwargs = {
            "file": {"validators": [FileSerializerValidator(['png', 'jpg', 'sql'], 10)]},
        }

    def create(self, validated_data):
        img_name = str(validated_data.get('img'))
        if not validated_data.get('name'):
            validated_data['name'] = img_name.split('.')[0]
        validated_data['mime_type'] = img_name.split('.')[-1].lower()
        if validated_data.get('img'):
            md5 = hashlib.md5()
            for chunk in validated_data.get('img').chunks():
                md5.update(chunk)
            validated_data['md5'] = md5.hexdigest()
            validated_data['size'] = validated_data.get('img').size

        instance = TestImageTable.objects.create(**validated_data)

        return instance


class TestImageUpdateSerializer(CustomModelSerializer):

    img = serializers.FileField(required=False, label='图片', help_text='图片')
    class Meta:
        model = TestImageTable
        # fields = '__all__'
        fields = ['id', 'name', 'img', 'create_datetime', 'mime_type', 'file']
        read_only_fields = ['id', 'create_datetime', 'mime_type']

    def update(self, instance, validated_data):

        if validated_data.get('img'):
            validated_data['mime_type'] = str(validated_data.get('img')).split('.')[-1].lower()
            md5 = hashlib.md5()
            for chunk in validated_data.get('img').chunks():
                md5.update(chunk)
            validated_data['md5'] = md5.hexdigest()
            validated_data['size'] = validated_data.get('img').size
        for k, v in validated_data.items():
            setattr(instance, k, v)
        instance.save()
        return instance


class TestApiSwagger(ViewSwagger):
    filter_file = ['id', 'create_datetime', 'mime_type']
    pro = ViewSwagger.req_serializer_form_schema(TestImageSerializer, filter_fields=filter_file)
    post_req_params = pro


@method_decorator([swagger_auto_schema(**TestApiSwagger.post())], name='create')
class TestImagesView(CustomView):
    """
    图片增、删、查
    tags:
        测试图片
    """
    parser_classes = [MultiPartParser, JSONParser]

    authentication_classes = []
    permission_classes = []

    queryset = TestImageTable.objects.all()
    serializer_class = TestImageSerializer
    pagination_class = CustomPagination


class TestImgPutView(CustomView):
    """
    修改图片
    tags:
        测试图片
    """
    authentication_classes = []
    permission_classes = []
    parser_classes = [MultiPartParser]

    queryset = TestImageTable.objects.all()
    serializer_class = TestImageUpdateSerializer
    lookup_field = 'pk'


# -----------------------------------------------------------------------------------------------------------

# 自定义过滤器
class UserTableFilter(django_filters.FilterSet):

    name = django_filters.CharFilter(field_name='name', lookup_expr='icontains', label='名字')

    select_fields = django_filters.CharFilter(method='select_fields_filter', label='选择的字段，可嵌套，示例：{id, name, group{id, name}}')

    def select_fields_filter(self, queryset, name, value):
        return queryset

    class Meta:

        model = TestUserTable
        fields = ['name', 'select_fields']


class UserTableSerializer(CustomModelSerializer):

    creator_field_id = 'user'
    modifier_field_id = 'user'

    class Meta:
        model = TestUserTable
        fields = "__all__"
        read_only_fields = ['id']
        extra_kwargs = {
            'user': {'required': False}
        }


class AuthObjectPermission(BasePermission):
    """
    验证用户有无该对象的权限
    """
    def has_object_permission(self, request, view, obj):
        user_id = request.user.id
        if obj.user_id == user_id:
            return True
        else:
            raise CustomValidationError(detail='未找到数据')


class TestUserTableView(CustomView):
    """
    tags:
        测试用户绑定数据
    """

    user_filter_fields = 'user_id'

    permission_classes = [IsAuthenticated, AuthObjectPermission]

    # filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filter_backends = [DjangoFilterBackend, ]
    filterset_class = UserTableFilter

    queryset = TestUserTable.objects.filter()
    serializer_class = UserTableSerializer
    pagination_class = CustomPagination
    lookup_field = 'pk'





